<?php
/**
 *
 *
 *
 */
class Yz_Form_Element_Input
    extends Yz_Form_Element_Abstract
{
    protected $element;
    protected $property;
    /** the element's form field value
     *  NOTE required in case the input value (eg from POST) could not be assigned and
     *      needs to be displayed as incorrect input
     *  @var string
     */
    protected $value = "";
    protected $isParseable = true;

    /**
     *  @param Yz_Form_Interface the form the element belongs to
     *  @param Traversable elements: [name: params]
     *      Params are passed to element constructor
     *  @param Yz_Property_Interface $element
     */
    public function __construct(
        Yz_Form_Interface $form,
        $name,
        Yz_Property_Interface $element
        )
    {
        debug();
        assert('is_string($name) and "" !== $name');
        $this->name = $name;
        $this->property = $element;
        $this->element =& $this->property;
        $this->form = $form;
        return;
    }


    /**
     *
     */
    public function render(Yz_Template_Interface $template)
    {
        $o = <<<html
            <input type="text" name="{$this->name}" value="{$this->value}" />\n
html;
        return $o;
    }


    /** 'parse' form-data array values to obtain correct value
     *      return boolean, whether the value is to be assigned
     *  @param mixed $value
     *  @return bool
     *  @throw Yz_Form_Element_Exception
     */
    public function parse($input)
    {
        debug("$this");
        try {
            $value = $this->validate($input);
        } catch (Yz_Exception $ex) {
            $this->exception = $ex;
            throw Yz_Form_Element_Exception::_new();
        }
        if ( null === $value and ! $this->allowEmpty() )
            throw new Yz_Form_Element_Exception("Empty value for element");
        $this->value = $value;
        return $value;
    }

    /********************************
     *        Protected methods     *
     *******************************/

    /**
     *
     *
     */
    protected function allowEmpty()
    {
        debug();
        return $this->property->allowNull();
    }


    /**
     *
     */
    protected function validate($input)
    {
        debug();
        if (! is_string($input))
            throw new Yz_Exception_InvalidValueType();
        $value = trim($input);
        if ("" === $value)
            $value = null;
        // assign value
        return $value;
    }
}
